const service = require('../../utils/service.js')
const api = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopInfo: {},
    userInfo: {},
    addressInfo: '',
    options: '',
    cart_ids: '',
    orderInfo: {},
    com_arr: [],
    is_yzc: 0,
    address_id: '',
    show_active: false,
    coupon_arr: [],
    selectId: '',
    countPrice: '',
    newArr: [],
    choic: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let cart_ids = '',
      option = '';
    if (options.cart_ids) {
      cart_ids = options.cart_ids
    } else {
      cart_ids = ""
    }
    if (options.options) {
      option = options.options
    } else {
      option = ""
    }

    if (options.is_yzc) {
      this.setData({
        is_yzc: 1
      })
    } else {
      this.setData({
        is_yzc: 0
      })
    }

    let shopInfo = wx.getStorageSync('shopInfo')
    let userInfo = wx.getStorageSync('shop_data')
    this.setData({
      shopInfo: shopInfo,
      userInfo: userInfo,
      options: option,
      cart_ids: cart_ids
    })
    if (options.address_id) {
      this.setData({
        address_id: options.address_id
      })
      this.getAddress()
    } else {
      this.getDefAddress()
    }
    this.init()
  },

  onShow: function () {
    this.getDefAddress()
  },

  init: function() {
    if (this.data.is_yzc) {
      this.confirmYzcOrder()
    } else {
      this.confirmOrder()
    }
  },

  // 获取默认收货地址
  getDefAddress: function() {
    let that = this
    api.ajax(service.url('getDefault'), {},function(res) {
      if (res.code == 0) {
        that.setData({
          addressInfo: res.data,
        })
        if (res.data.address_id) {
          that.setData({
            address_id: res.data.address_id
          })
        } else {
          that.setData({
            address_id: 0
          })
        }
      } else {
        api.toast(res.message)
      }
    })
  },

  // 根据address_id获取地址信息
  getAddress: function () {
    let that = this
    api.ajax(service.url('addressGet'), {
      unionid: that.data.userInfo.shop_unionid,
      address_id: that.data.address_id
    },
    function (res) {
      if (res.code == 0) {
        that.setData({
          addressInfo: res.data
        })
      } else {
        api.toast(res.message)
      }
    })
  },

  // 生成订单
  doPayOrder: function(e) {
    let that = this
    let arg
    // 留言字符串
    let comment_str = ''
    for (var i = 0, len = this.data.com_arr.length; i < len; i++) {
      comment_str += this.data.com_arr[i].str + '|'
    }

    // 优惠券字符串
    let coupon_str = ''
    for (var i = 0, len = this.data.coupon_arr.length; i < len; i++) {
      if (this.data.coupon_arr[i].use) {
        let str_a = this.data.coupon_arr[i].shop_id + ',' + this.data.coupon_arr[i].coupon_id
        coupon_str += str_a + '|'
      }
    }

    if (!that.data.address_id) {
      api.toast('请选择收货地址!')
      return
    }
    if (this.data.options) {
      // 普通购买
      arg = {
        unionid: that.data.userInfo.shop_unionid,
        options: that.data.options,
        comments: comment_str,
        address_id: that.data.addressInfo.address.address_id,
        coupons: coupon_str
      }
    } else if (this.data.cart_ids) {
      // 购物车购买
      arg = {
        unionid: that.data.userInfo.shop_unionid,
        cart_ids: that.data.cart_ids,
        comments: comment_str,
        address_id: that.data.addressInfo.address.address_id,
        coupons: coupon_str
      }
    }
    api.ajax(service.url('doPayOrder'), arg, function(res) {
      if (res.code == 0) {
        let pay_key = res.data.pay_key
        let money = res.data.total_amount
        wx.navigateTo({
          url: `../pay/pay?pay_key=${pay_key}&money=${money}`
        })
      } else {
        api.toast(res.message)
      }
    })
  },

  // 支付yzc商品
  convertOrder: function () {
    let that = this
    let comment_str = ''
    for (var i = 0, len = this.data.com_arr.length; i < len; i++) {
      comment_str += this.data.com_arr[i].str + '|'
    }
    if (!that.data.address_id) {
      api.toast('请选择收货地址!')
      return
    }
    api.ajax(service.url('convertOrder'), {
      options: that.data.options,
      comments: comment_str,
      address_id: that.data.addressInfo.address.address_id
    }, function (res) {
      if (res.code == 0) {
        wx.navigateTo({
          url: `../order/order?type=0`
        })
      } else {
        api.toast(res.message)
      }
    })
  },

  // 支付yzc
  toPay: function () {
    if (this.data.is_yzc) {
      let that = this
      wx.showModal({
        title: '提示',
        content: '是否用yzc兑换此商品?',
        confirmText: '兑换',
        success: (res) => {
          if (res.confirm) {
            that.convertOrder()
          }
        }
      })
    } else {
      this.doPayOrder()
    }
  },

  // 获取商品评论
  getComments: function(e) {
    let idx = e.currentTarget.dataset.id
    let val = e.detail.value
    let a = true
    let str = `${idx},${val}`
    let obj = {
      key: idx,
      str: str
    }
    if (this.data.com_arr.length == 0) {
      this.data.com_arr.push(obj)
    } else {
      for (var i = 0, len = this.data.com_arr.length; i < len; i++) {
        if (this.data.com_arr[i].key == idx) {
          a = true
          this.data.com_arr[i] = obj
        } else {
          a = false
        }
      }
      if (!a) {
        this.data.com_arr.push(obj)
      }
    }
    this.setData({
      com_arr: this.data.com_arr
    })
  },

  // 确认订单
  confirmOrder: function() {
    let that = this
    let arg
    if (this.data.options) {
      // 普通购买
      arg = {
        options: that.data.options
      }
    } else if (this.data.cart_ids) {
      // 购物车购买
      arg = {
        cart_ids: that.data.cart_ids
      }
    }
    api.ajax(service.url('confirmOrder'), arg, function(res) {
      if (res.code == 0) {
        for (var i = 0, len = res.data.shop_list.length; i < len; i++) {
          if (res.data.shop_list[i].coupon_list.length != 0) {
            var obj = {
              coupon_id: res.data.shop_list[i].coupon_list[0].coupon_discount_id,
              shop_id: res.data.shop_list[i].shop_code,
              use: false,
              amount: res.data.shop_list[i].coupon_list[0].amount,
            }
            that.data.coupon_arr.push(obj)
          }
        }

        that.setData({
          orderInfo: res.data,
          coupon_arr: that.data.coupon_arr,
          countPrice: res.data.goods_total_amount
        })
      } else {
        api.toast(res.message)
        setTimeout(function () {
          wx.navigateBack({
            delta: -1
          });
        },1000)
      }
    })
  },

  // yzc订单
  confirmYzcOrder: function () {
    let that = this
    api.ajax(service.url('confirmYzcOrder'), {
      options: that.data.options
    }, function (res) {
      if (res.code == 0) {
        that.setData({
          orderInfo: res.data
        })
      } else {
        api.toast(res.message)
      }
    })
  },

  // 前往商品详情
  toGoods: function(e) {
    let goods_id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `../goods_detail/goods_detail?goods_id=${goods_id}`,
    })
  },

  // 去选择收货地址
  toSelectAddress: function() {
    let address_id = this.data.addressInfo.address_id
    wx.navigateTo({
      url: `../select_address/select_address?options=${this.data.options}&address_id=${address_id}`
    })
  },

  hidePon: function () {
    this.setData({
      show_active: false
    })
  },

  // 是否使用优惠券
  showPon: function (e) {
    let shop_id = e.currentTarget.dataset.shopid
    let idx = e.currentTarget.dataset.index
    this.setData({
      choic: false
    })
    this.setData({
      show_active: true,
      selectId: shop_id,
      orderInfo: this.data.orderInfo,
      newArr: this.data.orderInfo.shop_list[idx].coupon_list
    })
  },

  // 选择优惠券
  radioChange: function (e) {
    let shop_id = this.data.selectId
    let is_use = e.detail.value
    for (var i = 0, len = this.data.coupon_arr.length; i < len; i++) {
      if (shop_id == this.data.coupon_arr[i].shop_id) {
        if (is_use == 0) {
          this.data.coupon_arr[i].use = false
        } else {
          this.data.coupon_arr[i].use = true
          this.data.coupon_arr[i].coupon_id = is_use
        }
      }
    }

    this.setData({
      coupon_arr: this.data.coupon_arr
    })
    this.hidePon()
    this.countAll()
  },

  // 计算优惠后的价格
  countAll: function () {
    var num = 0
    var allCount = 0
    for (var i = 0, len = this.data.orderInfo.shop_list.length; i < len; i++ ) {
      for (var j = 0, len2 = this.data.coupon_arr.length; j < len2; j++) {
        if (this.data.orderInfo.shop_list[i].shop_code == this.data.coupon_arr[j].shop_id) {
          if (this.data.coupon_arr[j].use) {
            num = this.data.orderInfo.shop_list[i].goods_amount - this.data.coupon_arr[j].amount
          }
          else{
            num = this.data.orderInfo.shop_list[i].goods_amount
          }
          allCount += num;
        }
      }
    }
    this.setData({
      countPrice: parseFloat(allCount).toFixed(2)
    })
  }
})
